import 'package:pacsun/model/taskModel.dart';
import 'package:pacsun/provider/taskDetailProv.dart';
import 'package:pacsun/provider/taskListProv.dart';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';
import '../mediaPicker/mediaPickerPage.dart';
import 'widgets/photoGrid.dart';
import 'widgets/titleInput.dart';
import 'widgets/descriptionInput.dart';
import 'widgets/tagsSection.dart';
import 'widgets/productLinkSection.dart';
import '../../../provider/tagProvider.dart';
import '../../../provider/contentProvider.dart';
import '../../../model/bgcContentSave.dart';
import '../../../services/uploadService.dart';
import 'dart:convert';
import '../../../provider/userProv.dart';
import '../../../model/draftModel.dart';
import '../../../model/mediaItem.dart';
import '../../../services/contentService.dart';
import '../../../widgets/toastMenu.dart';

class PublishPage extends StatefulWidget {
  final List<AssetEntity> selectedPhotos;
  final List<AssetEntity> selectedVideos;
  final int? taskConfigId;
  final int? taskRecordId;
  final bool loadDraftOnInit;

  const PublishPage({
    Key? key,
    this.selectedPhotos = const [],
    this.selectedVideos = const [],
    this.taskConfigId,
    this.taskRecordId,
    this.loadDraftOnInit = false,
  }) : super(key: key);

  @override
  State<PublishPage> createState() => _PublishPageState();
}

class _PublishPageState extends State<PublishPage> {
  late List<MediaItem> currentMediaItems;

  TextEditingController titleController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  // 添加FocusNode用于两个输入框
  FocusNode titleFocusNode = FocusNode();
  FocusNode descriptionFocusNode = FocusNode();

  // 添加键盘工具栏显示状态
  bool _showKeyboardToolbar = false;

  int maxTitleLength = 70;
  Set<int> addedTags = {};
  final UploadService _uploadService = UploadService();

  // 添加loading状态变量
  bool _isSavingDraft = false;
  bool _isPublishing = false;
  bool _isLoadingDraft = false;

  // 添加用户AID变量
  String? userAid;

  // 添加草稿ID变量
  int? currentDraftId;

  // 添加变量来存储从草稿加载的任务信息
  int? actualTaskConfigId;
  int? actualTaskRecordId;

  // 添加任务相关标签变量
  List<String> taskRelatedTags = [];

  @override
  void initState() {
    super.initState();

    // 初始化混合媒体列表
    currentMediaItems = [
      ...widget.selectedPhotos.map((asset) => LocalMediaItem(asset)),
      ...widget.selectedVideos.map((asset) => LocalMediaItem(asset)),
    ];

    // 监听两个输入框的焦点变化
    titleFocusNode.addListener(_onFocusChange);
    descriptionFocusNode.addListener(_onFocusChange);

    // 在页面初始化时获取标签和商品数据，以及用户AID
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 获取用户AID
      final userProvider = context.read<UserProvider>();
      if (userProvider.currentUser != null) {
        userAid = userProvider.currentUser!.aid;
      }

      context.read<TagProvider>().fetchTags();

      // 获取任务相关标签并添加到描述框
      _loadTaskRelatedTags();

      // 如果需要加载草稿，则获取草稿数据
      if (widget.loadDraftOnInit && widget.taskRecordId != null) {
        _loadDraftData();
      }
    });
  }

  @override
  void dispose() {
    titleController.dispose();
    descriptionController.dispose();
    titleFocusNode.removeListener(_onFocusChange);
    descriptionFocusNode.removeListener(_onFocusChange);
    titleFocusNode.dispose();
    descriptionFocusNode.dispose();
    super.dispose();
  }

  // 监听任一输入框焦点变化
  void _onFocusChange() {
    if (mounted) {
      setState(() {
        _showKeyboardToolbar =
            titleFocusNode.hasFocus || descriptionFocusNode.hasFocus;
      });
    }
  }

  // 检查是否有内容需要保存
  bool _hasContentToSave() {
    return currentMediaItems.isNotEmpty ||
        titleController.text.trim().isNotEmpty ||
        descriptionController.text.trim().isNotEmpty ||
        addedTags.isNotEmpty;
  }

  // 处理返回操作
  Future<bool> _onWillPop() async {
    // 如果正在loading，阻止返回
    if (_isSavingDraft || _isPublishing) {
      return false;
    }

    if (_hasContentToSave()) {
      return await _showSaveDraftDialog() ?? false;
    }
    return true;
  }

  // 显示保存草稿确认对话框
  Future<bool?> _showSaveDraftDialog() async {
    return showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Color(0xFF2C2C2C),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 20),
              Text(
                'Do you want to save\nthe draft ?',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 30),
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Color(0xFF6B6B6B),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25),
                        ),
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(true); // 不保存，直接返回
                      },
                      child: Text(
                        'NO',
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 16),
                  Expanded(
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.red,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25),
                        ),
                        padding: EdgeInsets.symmetric(vertical: 12),
                      ),
                      onPressed: () async {
                        Navigator.of(context).pop(false); // 关闭对话框
                        await _saveDraftAndExit(); // 保存草稿并退出
                      },
                      child: Text(
                        'YES',
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 10),
            ],
          ),
        );
      },
    );
  }

  // 保存草稿并退出
  Future<void> _saveDraftAndExit() async {
    setState(() {
      _isSavingDraft = true;
    });

    try {
      await _performSaveDraft(
          context.read<TaskDetailProv>(), context.read<TaskListProv>());

      if (mounted) {
        setState(() {
          _isSavingDraft = false;
        });
        _showSaveSuccessToast();

        // 延迟一下再退出，让用户看到成功提示
        await Future.delayed(Duration(milliseconds: 1500));
        if (mounted) {
          Navigator.of(context).pop();
        }
      }
    } catch (e) {
      _showErrorDialog('Draft save failed');
      if (mounted) {
        setState(() {
          _isSavingDraft = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Stack(
        children: [
          Scaffold(
            backgroundColor: Colors.black,
            appBar: _buildAppBar(),
            // 添加 resizeToAvoidBottomInset 来确保页面随键盘调整
            resizeToAvoidBottomInset: true,
            body: _isLoadingDraft
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(color: Colors.white),
                        SizedBox(height: 16),
                        Text(
                          'Loading draft...',
                          style: TextStyle(color: Colors.white, fontSize: 16),
                        ),
                      ],
                    ),
                  )
                : Column(
                    children: [
                      Expanded(
                        child: GestureDetector(
                          // 添加GestureDetector来处理点击空白区域关闭键盘
                          onTap: () {
                            FocusScope.of(context).unfocus();
                          },
                          child: SingleChildScrollView(
                            padding: EdgeInsets.all(16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // 使用更稳定的key，避免不必要的重建
                                RepaintBoundary(
                                  child: PhotoGrid(
                                    key: ValueKey(
                                        'photo_grid_stable'), // 使用稳定的key
                                    photos: currentPhotos,
                                    videos: currentVideos,
                                    mediaItems: currentMediaItems,
                                    onAddMore: _addMorePhotos,
                                    onRemove: _removePhoto,
                                  ),
                                ),
                                SizedBox(height: 24),
                                RepaintBoundary(
                                  child: TitleInput(
                                    controller: titleController,
                                    maxLength: maxTitleLength,
                                    onChanged: null,
                                    focusNode:
                                        titleFocusNode, // 传递titleFocusNode
                                    descriptionFocusNode:
                                        descriptionFocusNode, // 传递descriptionFocusNode
                                  ),
                                ),
                                SizedBox(height: 16),
                                DescriptionInput(
                                  controller: descriptionController,
                                  focusNode:
                                      descriptionFocusNode, // 传递focusNode
                                ),
                                SizedBox(height: 24),
                                _buildTagsSection(),
                                SizedBox(height: 24),
                                _buildProductLinkSection(),
                              ],
                            ),
                          ),
                        ),
                      ),
                      // 键盘上方工具栏
                      if (_showKeyboardToolbar) _buildKeyboardToolbar(),
                    ],
                  ),
          ),
          if (_isSavingDraft || _isPublishing) _buildFullScreenLoading(),
        ],
      ),
    );
  }

  Widget _buildTagsSection() {
    return Consumer<TagProvider>(
      builder: (context, tagProvider, child) {
        if (tagProvider.isLoading) {
          return Container(
            height: 50,
            child: Center(
              child: CircularProgressIndicator(color: Colors.white),
            ),
          );
        }

        // 过滤掉与任务相关标签重复的标签
        List<String> filteredTags =
            tagProvider.tags.map((tag) => tag.displayName).where((tagName) {
          // 检查是否与任务相关标签重复（忽略大小写和#符号）
          String normalizedTagName = tagName.toLowerCase().replaceAll('#', '');
          return !taskRelatedTags.any((taskTag) {
            String normalizedTaskTag =
                taskTag.toLowerCase().replaceAll('#', '');
            return normalizedTaskTag == normalizedTagName;
          });
        }).toList();

        print('=== 标签过滤结果 ===');
        print('原始标签数量: ${tagProvider.tags.length}');
        print('任务相关标签: $taskRelatedTags');
        print('过滤后标签数量: ${filteredTags.length}');
        print('过滤后标签: $filteredTags');
        print('===================');

        return TagsSection(
          tags: filteredTags, // 使用过滤后的标签
          addedTags: addedTags,
          onTagTap: _addTagToDescription,
        );
      },
    );
  }

  Widget _buildProductLinkSection() {
    return Consumer<TaskDetailProv>(
      builder: (context, taskDetailProv, child) {
        List<ProductModel> productList = taskDetailProv.productList ?? [];

        return ProductLinkSection(
          products: productList,
          onTap: () =>
              ToastMenu.showToast(context, 'Function under development'),
        );
      },
    );
  }

  AppBar _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.black,
      elevation: 0,
      leading: BackButton(color: Colors.white),
      actions: [
        Container(
          margin: EdgeInsets.only(right: 8, top: 8, bottom: 8),
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: _isSavingDraft || _isPublishing
                  ? Colors.grey
                  : Color(0x806B6B6B),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: BorderSide(color: Color(0xFFEFEFEF), width: 1),
              ),
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            ),
            onPressed: _isSavingDraft || _isPublishing ? null : _saveDraft,
            child: Text(
              'SAVE DRAFT',
              style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 12),
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(right: 16, top: 8, bottom: 8),
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor:
                  _isPublishing || _isSavingDraft ? Colors.grey : Colors.red,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20)),
              padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
            ),
            onPressed: _isPublishing || _isSavingDraft ? null : _publish,
            child: Text(
              'PUBLISH',
              style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 12),
            ),
          ),
        ),
      ],
    );
  }

  void _addMorePhotos() async {
    // 在跳转前先保存当前状态
    final currentNetworkItems =
        currentMediaItems.where((item) => item.isNetworkImage).toList();

    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => MediaPickerPage(
          initialSelectedPhotos: currentPhotos,
          initialSelectedVideos: currentVideos,
          taskConfigId: widget.taskConfigId,
          taskRecordId: widget.taskRecordId,
          networkImageCount: currentNetworkItems.length,
          isFromPublishPage: true, // 明确标识从PublishPage跳转
        ),
      ),
    );

    if (result != null && result is Map<String, dynamic>) {
      setState(() {
        // 重新获取网络图片（防止页面重建时丢失）
        List<MediaItem> networkItems = currentNetworkItems;

        List<MediaItem> newLocalPhotos =
            (result['photos'] as List<AssetEntity>?)
                    ?.map((asset) => LocalMediaItem(asset))
                    .toList() ??
                [];

        List<MediaItem> newLocalVideos =
            (result['videos'] as List<AssetEntity>?)
                    ?.map((asset) => LocalMediaItem(asset))
                    .toList() ??
                [];

        currentMediaItems = [
          ...networkItems,
          ...newLocalPhotos,
          ...newLocalVideos
        ];
      });
    }
  }

  void _removePhoto(int index) {
    if (index < currentMediaItems.length) {
      setState(() {
        currentMediaItems.removeAt(index);
      });
    }
  }

  void _addTagToDescription(String tag, int tagIndex) {
    setState(() {
      addedTags.add(tagIndex);
      String currentText = descriptionController.text;
      if (currentText.isNotEmpty && !currentText.endsWith(' ')) {
        currentText += ' ';
      }
      descriptionController.text = currentText + tag + ' ';
      descriptionController.selection = TextSelection.fromPosition(
        TextPosition(offset: descriptionController.text.length),
      );
    });
  }

  void _publish() async {
    final Stopwatch totalPublishStopwatch = Stopwatch()..start();

    // 验证表单
    if (titleController.text.trim().isEmpty) {
      ToastMenu.showToast(context, 'Please enter a title');
      return;
    }

    if (currentMediaItems.isEmpty) {
      ToastMenu.showToast(context, 'Please select at least one image or video');
      return;
    }

    setState(() {
      _isPublishing = true;
    });

    try {
      print('=== 开始发布流程 ===');
      print('发布开始时间: ${DateTime.now()}');
      print('总媒体数量: ${currentMediaItems.length}');
      print('网络图片数量: ${networkImageUrls.length}');
      print('本地图片数量: ${currentPhotos.length}');
      print('本地视频数量: ${currentVideos.length}');
      print('widget.taskConfigId: ${widget.taskConfigId}');
      print('widget.taskRecordId: ${widget.taskRecordId}');
      print('currentDraftId: $currentDraftId');

      final contentProvider = context.read<ContentProvider>();
      final taskDetailProv = context.read<TaskDetailProv>();
      final taskListProv = context.read<TaskListProv>();

      // 判断是否从主页进入：没有taskConfigId和taskRecordId
      bool isFromHomePage =
          widget.taskConfigId == null && widget.taskRecordId == null;

      if (isFromHomePage) {
        print('=== 从主页进入，使用直接发布流程 ===');
        // 从主页进入时，无论是否有草稿ID，都使用直接发布
        await _performDirectPublish(
            contentProvider, taskDetailProv, taskListProv);
      } else {
        // 从任务页面进入，根据是否有currentDraftId来决定流程
        if (currentDraftId != null) {
          print('=== 从任务页面进入，有草稿ID，使用草稿发布流程 ===');
          print('草稿ID: $currentDraftId');

          // 先保存/更新草稿，然后发布
          await _performSaveDraftForPublish();

          // 发布草稿
          await _performPublishDraft(
              contentProvider, taskDetailProv, taskListProv);
        } else {
          print('=== 从任务页面进入，没有草稿ID，使用直接发布流程 ===');

          // 直接发布逻辑
          await _performDirectPublish(
              contentProvider, taskDetailProv, taskListProv);
        }
      }

      totalPublishStopwatch.stop();
      print('=== 发布流程完成 ===');
      print('发布结束时间: ${DateTime.now()}');
      print(
          '发布总耗时: ${totalPublishStopwatch.elapsedMilliseconds}ms (${(totalPublishStopwatch.elapsedMilliseconds / 1000).toStringAsFixed(2)}秒)');
      print('====================');
    } catch (e) {
      totalPublishStopwatch.stop();
      print('=== 发布流程失败 ===');
      print('失败时间: ${DateTime.now()}');
      print('失败前总耗时: ${totalPublishStopwatch.elapsedMilliseconds}ms');
      print('错误信息: $e');
      print('==================');
      _showErrorDialog('Publish failed');
    } finally {
      if (mounted) {
        setState(() {
          _isPublishing = false;
        });
      }
    }
  }

  // 获取任务相关标签的方法
  void _loadTaskRelatedTags() {
    final taskDetailProv = context.read<TaskDetailProv>();

    // 获取任务标签名称
    List<String> taskTagNames = taskDetailProv.taskTagNames;

    if (taskTagNames.isNotEmpty) {
      // 为每个标签添加#前缀
      taskRelatedTags = taskTagNames.map((tag) => '#$tag').toList();

      // 将任务相关标签添加到描述框中
      String tagsText = taskRelatedTags.join(' ') + ' ';

      // 如果描述框已经有内容，在后面添加标签
      String currentText = descriptionController.text;
      if (currentText.isNotEmpty && !currentText.endsWith(' ')) {
        currentText += ' ';
      }

      descriptionController.text = currentText + tagsText;
      descriptionController.selection = TextSelection.fromPosition(
        TextPosition(offset: descriptionController.text.length),
      );

      print('=== 任务相关标签已添加到描述框 ===');
      print('任务标签: $taskRelatedTags');
      print('描述框内容: ${descriptionController.text}');
      print('==============================');
    }
  }

  // 修改草稿数据填充方法，处理任务标签
  void _populateFieldsFromDraft(DraftModel draftData) {
    setState(() {
      // 保存草稿ID
      currentDraftId = draftData.id;

      // 从草稿数据中获取任务信息
      actualTaskConfigId = draftData.taskRecordBo?.taskConfig?.id;
      actualTaskRecordId = draftData.taskRecordId;

      // 填充标题和内容
      titleController.text = draftData.title;
      descriptionController.text = draftData.content;

      // 添加网络图片到媒体列表
      List<MediaItem> networkImages = draftData.images
          .map((url) => NetworkMediaItem(url, AssetType.image))
          .toList();

      // 将网络图片添加到现有媒体列表的开头
      currentMediaItems = [...networkImages, ...currentMediaItems];

      // 重新获取任务相关标签（如果从草稿加载）
      if (actualTaskConfigId != null) {
        Future.delayed(Duration(milliseconds: 100), () {
          _loadTaskRelatedTags();
        });
      }

      print('=== 草稿数据已填充 ===');
      print('草稿ID: $currentDraftId');
      print('actualTaskConfigId: $actualTaskConfigId');
      print('actualTaskRecordId: $actualTaskRecordId');
      print('标题: ${titleController.text}');
      print('内容: ${descriptionController.text}');
      print('网络图片数量: ${networkImages.length}');
      print('总媒体数量: ${currentMediaItems.length}');
      print('====================');
    });
  }

  // 修改为发布保存草稿的方法
  Future<void> _performSaveDraftForPublish() async {
    print('=== 开始为发布保存草稿 ===');

    // 检查用户是否已登录
    if (userAid == null) {
      throw Exception('用户未登录，无法保存草稿');
    }

    // 获取任务参数：优先使用从草稿加载的，其次使用widget参数，最后允许为null（首页发布）
    final taskConfigId = actualTaskConfigId ?? widget.taskConfigId;
    final taskRecordId = actualTaskRecordId ?? widget.taskRecordId;

    print('=== 任务参数检查 ===');
    print('taskConfigId: $taskConfigId');
    print('taskRecordId: $taskRecordId');
    print('currentDraftId: $currentDraftId');
    print('===================');

    // 1. 只上传本地图片
    List<String> newImageUrls = [];
    String? thumbnailUrl;
    if (currentPhotos.isNotEmpty) {
      print('开始上传本地图片...');
      final Map<String, dynamic> imageResult =
          await _uploadService.uploadImagesWithThumbnail(currentPhotos);
      newImageUrls = List<String>.from(imageResult['imageUrls'] ?? []);
      thumbnailUrl = imageResult['thumbnailUrl'];
    }

    // 2. 处理视频上传
    String? videoUrl;
    if (currentVideos.isNotEmpty) {
      print('开始上传视频...');
      final AssetEntity videoAsset = currentVideos.first;
      final Map<String, String> videoResult =
          await _uploadService.uploadVideoWithThumbnail(videoAsset);
      videoUrl = videoResult['videoUrl'];

      // 如果没有图片缩略图，则使用视频缩略图
      if (thumbnailUrl == null) {
        thumbnailUrl = videoResult['thumbnailUrl'];
      }
    }

    // 3. 合并网络图片URL和新上传的URL
    List<String> allImageUrls = [...networkImageUrls, ...newImageUrls];

    // 4. 准备标签数据
    List<TaskTagBo> taskTagBoList = _prepareTaskTagBoList();

    // 5. 创建保存请求（允许taskConfigId和taskRecordId为null）
    BgcContentSave contentSave = BgcContentSave(
      aid: userAid!,
      title: titleController.text.trim(),
      content: descriptionController.text.trim(),
      richContent: descriptionController.text.trim(),
      images: allImageUrls,
      videos: videoUrl,
      thumbnail: thumbnailUrl,
      taskTagBoList: taskTagBoList,
      taskConfigId: taskConfigId, // 允许为null
      taskRecordId: taskRecordId, // 允许为null
      id: currentDraftId,
    );

    print('=== 草稿保存请求数据 ===');
    print('完整请求数据: ${contentSave.toJson()}');
    print('=========================');

    // 6. 调用保存草稿API并获取返回信息
    final contentService = ContentService();

    if (currentDraftId != null) {
      // 更新草稿时，如果没有taskRecordId则报错
      if (taskRecordId == null) {
        throw Exception('更新草稿需要taskRecordId，但当前为空');
      }

      await contentService.updateDraft(contentSave);
      print('草稿更新完成，草稿ID: $currentDraftId');
    } else {
      // 创建新草稿，使用新的saveDraft方法
      final savedDraftModel = await contentService.saveDraft(contentSave);

      // 更新本地状态
      setState(() {
        currentDraftId = savedDraftModel.id;

        // 重要：从保存草稿响应中获取taskRecordId
        if (savedDraftModel.taskRecordId != 0 && actualTaskRecordId == null) {
          actualTaskRecordId = savedDraftModel.taskRecordId;
          print('从保存草稿响应获取taskRecordId: $actualTaskRecordId');
        }
      });

      print('新草稿创建成功');
      print('草稿ID: $currentDraftId');
      print('taskRecordId: ${savedDraftModel.taskRecordId}');
      print('所有图片URLs: ${savedDraftModel.images}');
      print('缩略图URL: ${savedDraftModel.thumbnail}');
    }

    print('为发布保存草稿完成，草稿ID: $currentDraftId');
  }

  // 修改发布草稿方法
  Future<void> _performPublishDraft(ContentProvider contentProvider,
      TaskDetailProv taskDetailProv, TaskListProv taskListProv) async {
    print('=== 开始发布草稿 ===');
    print('草稿ID: $currentDraftId');

    if (currentDraftId == null) {
      throw Exception('草稿ID为空，无法发布');
    }

    // 获取任务参数（现在应该已经从保存草稿响应中获取了）
    final taskConfigId = actualTaskConfigId ?? widget.taskConfigId;
    final taskRecordId = actualTaskRecordId ?? widget.taskRecordId;

    // 从最新保存的草稿中获取完整信息
    final savedDraft = contentProvider.savedDraft;

    // 1. 使用保存草稿后的完整数据
    List<String> allImageUrls = savedDraft?.images ?? [...networkImageUrls];
    String? videoUrl; // DraftModel没有videos字段，需要从其他地方获取
    String? thumbnailUrl = savedDraft?.thumbnail;
    int? actualTaskRecordIdFromSave = savedDraft?.taskRecordId ?? taskRecordId;
    int? actualTaskConfigIdFromSave = taskConfigId;

    // 如果有本地视频，重新获取视频URL
    if (currentVideos.isNotEmpty) {
      final AssetEntity videoAsset = currentVideos.first;
      final Map<String, String> videoResult =
          await _uploadService.uploadVideoWithThumbnail(videoAsset);
      videoUrl = videoResult['videoUrl'];
    }

    print('发布草稿使用的数据:');
    print('图片URLs: $allImageUrls');
    print('视频URL: $videoUrl');
    print('缩略图URL: $thumbnailUrl');
    print('taskRecordId: $actualTaskRecordIdFromSave');
    print('taskConfigId: $actualTaskConfigIdFromSave');

    // 2. 准备标签数据
    List<TaskTagBo> taskTagBoList = _prepareTaskTagBoList();

    // 3. 创建发布草稿请求数据
    BgcContentSave publishDraftSave = BgcContentSave(
      aid: userAid!,
      title: titleController.text.trim(),
      content: descriptionController.text.trim(),
      richContent: descriptionController.text.trim(),
      images: allImageUrls,
      videos: videoUrl,
      thumbnail: thumbnailUrl,
      taskTagBoList: taskTagBoList,
      taskConfigId: actualTaskConfigIdFromSave,
      taskRecordId: actualTaskRecordIdFromSave,
      id: currentDraftId,
    );

    print('=== 发布草稿请求数据 ===');
    print('草稿ID: ${publishDraftSave.id}');
    print('taskRecordId: ${publishDraftSave.taskRecordId}');
    print('taskConfigId: ${publishDraftSave.taskConfigId}');
    print('图片数量: ${publishDraftSave.images.length}');
    print('=======================');

    // 4. 调用发布草稿API
    await contentProvider.publishDraftWithData(publishDraftSave);

    // 5. 刷新任务状态
    final finalTaskRecordId = contentProvider.taskRecordId != 0
        ? contentProvider.taskRecordId
        : actualTaskRecordIdFromSave ?? 0;

    taskDetailProv.refreshTaskDetail(finalTaskRecordId, 'My Tasks');
    taskListProv.refreshTaskList();

    if (contentProvider.publishError != null) {
      _showErrorDialog('Publish failed');
    } else {
      _showSubmitSuccessToast();
    }
  }

  // 修改直接发布方法
  Future<void> _performDirectPublish(ContentProvider contentProvider,
      TaskDetailProv taskDetailProv, TaskListProv taskListProv) async {
    // 获取任务参数（允许为null，用于首页发布）
    final taskConfigId = actualTaskConfigId ?? widget.taskConfigId;
    final taskRecordId = actualTaskRecordId ?? widget.taskRecordId;

    // 1. 上传本地图片和视频文件
    List<String> newImageUrls = [];
    String? videoUrl;
    String? thumbnailUrl;

    // 上传本地图片时间统计
    if (currentPhotos.isNotEmpty) {
      final Stopwatch imageUploadStopwatch = Stopwatch()..start();
      print('开始上传本地图片和生成缩略图...');

      // 使用新的方法同时上传图片和缩略图
      final Map<String, dynamic> imageResult =
          await _uploadService.uploadImagesWithThumbnail(currentPhotos);
      newImageUrls = List<String>.from(imageResult['imageUrls'] ?? []);
      thumbnailUrl = imageResult['thumbnailUrl'];

      imageUploadStopwatch.stop();
      print('本地图片和缩略图上传完成 (耗时: ${imageUploadStopwatch.elapsedMilliseconds}ms)');
      print('新上传图片URLs: $newImageUrls');
      print('缩略图URL: $thumbnailUrl');
    }

    // 上传视频时间统计
    if (currentVideos.isNotEmpty) {
      final Stopwatch videoUploadStopwatch = Stopwatch()..start();
      print('开始上传视频和视频缩略图...');

      // 只处理第一个视频
      final AssetEntity videoAsset = currentVideos.first;
      final Map<String, String> videoResult =
          await _uploadService.uploadVideoWithThumbnail(videoAsset);
      videoUrl = videoResult['videoUrl'];

      // 如果没有图片缩略图，则使用视频缩略图
      if (thumbnailUrl == null) {
        thumbnailUrl = videoResult['thumbnailUrl'];
        print('使用视频缩略图: $thumbnailUrl');
      } else {
        print('已有图片缩略图，视频缩略图将被忽略');
      }

      videoUploadStopwatch.stop();
      print(
          '视频上传完成 (耗时: ${videoUploadStopwatch.elapsedMilliseconds}ms): $videoUrl');
    }

    // 2. 合并网络图片URL和新上传的本地图片URL
    List<String> allImageUrls = [...networkImageUrls, ...newImageUrls];
    print('=== 图片URL合并结果 ===');
    print('网络图片URLs: $networkImageUrls');
    print('新上传图片URLs: $newImageUrls');
    print('合并后所有图片URLs: $allImageUrls');
    print('========================');

    // 3. 准备标签数据
    final Stopwatch tagPrepStopwatch = Stopwatch()..start();
    List<TaskTagBo> taskTagBoList = _prepareTaskTagBoList(); // 使用新的方法
    tagPrepStopwatch.stop();
    print('标签数据准备完成 (耗时: ${tagPrepStopwatch.elapsedMilliseconds}ms)');

    // 4. 创建发布请求数据
    final Stopwatch dataStopwatch = Stopwatch()..start();
    BgcContentSave contentSave = BgcContentSave(
        aid: userAid!,
        title: titleController.text.trim(),
        content: descriptionController.text.trim(),
        richContent: descriptionController.text.trim(),
        images: allImageUrls,
        videos: videoUrl,
        thumbnail: thumbnailUrl,
        taskTagBoList: taskTagBoList,
        taskConfigId: taskConfigId, // 允许为null
        taskRecordId: taskRecordId); // 允许为null
    dataStopwatch.stop();

    // 输出请求数据用于调试
    print('=== 发布请求数据 ===');
    print('数据构建耗时: ${dataStopwatch.elapsedMilliseconds}ms');
    print('userAid: $userAid');
    print('所有图片URLs: $allImageUrls');
    print('视频URL: $videoUrl');
    print('缩略图URL: $thumbnailUrl');
    print('Request Body: ${contentSave.toJson()}');
    print('JSON String: ${jsonEncode(contentSave.toJson())}');
    print('==================');

    // 5. 调用发布API
    final Stopwatch publishApiStopwatch = Stopwatch()..start();
    await contentProvider.publishContent(contentSave);
    publishApiStopwatch.stop();
    print('发布API调用完成 (耗时: ${publishApiStopwatch.elapsedMilliseconds}ms)');

    // 6. 刷新任务状态
    final Stopwatch refreshStopwatch = Stopwatch()..start();
    taskDetailProv.refreshTaskDetail(contentProvider.taskRecordId, 'My Tasks');
    taskListProv.refreshTaskList();
    refreshStopwatch.stop();
    print('任务状态刷新完成 (耗时: ${refreshStopwatch.elapsedMilliseconds}ms)');

    if (contentProvider.publishError != null) {
      _showErrorDialog('Publish failed');
    } else {
      _showSubmitSuccessToast();
    }
  }

  // 修改保存草稿方法
  Future<void> _performSaveDraft(
      TaskDetailProv taskDetailProv, TaskListProv taskListProv) async {
    // 获取任务参数（允许为null）
    final taskConfigId = actualTaskConfigId ?? widget.taskConfigId;
    final taskRecordId = actualTaskRecordId ?? widget.taskRecordId;

    final Stopwatch totalDraftStopwatch = Stopwatch()..start();

    // 检查用户是否已登录
    if (userAid == null) {
      throw Exception('用户未登录，无法保存草稿');
    }

    // 判断是否从首页进入：没有taskConfigId和taskRecordId
    bool isFromHomePage =
        widget.taskConfigId == null && widget.taskRecordId == null;

    print('=== 开始保存草稿流程 ===');
    print('当前草稿ID: $currentDraftId');
    print('是否从首页进入: $isFromHomePage');
    print('taskConfigId: $taskConfigId');
    print('taskRecordId: $taskRecordId');

    // 1. 只上传本地图片
    List<String> newImageUrls = [];
    String? thumbnailUrl;
    if (currentPhotos.isNotEmpty) {
      final Stopwatch imageUploadStopwatch = Stopwatch()..start();
      print('开始上传图片和生成缩略图...');

      final Map<String, dynamic> imageResult =
          await _uploadService.uploadImagesWithThumbnail(currentPhotos);
      newImageUrls = List<String>.from(imageResult['imageUrls'] ?? []);
      thumbnailUrl = imageResult['thumbnailUrl'];

      imageUploadStopwatch.stop();
      print('图片和缩略图上传完成 (耗时: ${imageUploadStopwatch.elapsedMilliseconds}ms)');
      print('图片URLs: $newImageUrls');
      print('缩略图URL: $thumbnailUrl');
    }

    // 2. 处理视频上传
    String? videoUrl;
    if (currentVideos.isNotEmpty) {
      final Stopwatch videoUploadStopwatch = Stopwatch()..start();
      print('开始上传视频和视频缩略图...');

      // 只处理第一个视频
      final AssetEntity videoAsset = currentVideos.first;
      final Map<String, String> videoResult =
          await _uploadService.uploadVideoWithThumbnail(videoAsset);
      videoUrl = videoResult['videoUrl'];

      // 如果没有图片缩略图，则使用视频缩略图
      if (thumbnailUrl == null) {
        thumbnailUrl = videoResult['thumbnailUrl'];
        print('使用视频缩略图: $thumbnailUrl');
      } else {
        print('已有图片缩略图，视频缩略图将被忽略');
      }

      videoUploadStopwatch.stop();
      print(
          '视频上传完成 (耗时: ${videoUploadStopwatch.elapsedMilliseconds}ms): $videoUrl');
    }

    // 3. 合并网络图片URL和新上传的URL
    List<String> allImageUrls = [...networkImageUrls, ...newImageUrls];

    // 4. 准备标签数据
    final Stopwatch tagPrepStopwatch = Stopwatch()..start();
    List<TaskTagBo> taskTagBoList = _prepareTaskTagBoList();
    tagPrepStopwatch.stop();
    print('标签数据准备完成 (耗时: ${tagPrepStopwatch.elapsedMilliseconds}ms)');

    // 5. 创建保存请求
    final Stopwatch dataStopwatch = Stopwatch()..start();
    BgcContentSave contentSave = BgcContentSave(
      aid: userAid!,
      title: titleController.text.trim(),
      content: descriptionController.text.trim(),
      richContent: descriptionController.text.trim(),
      images: allImageUrls,
      videos: videoUrl,
      thumbnail: thumbnailUrl,
      taskTagBoList: taskTagBoList,
      taskConfigId: taskConfigId, // 允许为null
      taskRecordId: taskRecordId, // 允许为null
      id: currentDraftId,
    );
    dataStopwatch.stop();

    print('=== 草稿保存参数检查 ===');
    print('数据构建耗时: ${dataStopwatch.elapsedMilliseconds}ms');
    print('userAid: $userAid');
    print('currentDraftId: $currentDraftId');
    print('taskConfigId: $taskConfigId');
    print('taskRecordId: $taskRecordId');
    print('========================');

    // 6. 调用保存草稿API
    final Stopwatch apiStopwatch = Stopwatch()..start();
    final contentService = ContentService();

    // 修改判断逻辑：从首页进入时，即使有currentDraftId也使用保存草稿API
    if (currentDraftId != null && !isFromHomePage && taskRecordId != null) {
      // 更新现有草稿（仅限从任务页面进入且有taskRecordId的情况）
      print('更新现有草稿，ID: $currentDraftId');
      await contentService.updateDraft(contentSave);
    } else {
      // 创建新草稿（首页进入时总是创建新草稿，或者从任务页面进入但没有草稿ID）
      print('创建新草稿（从首页进入或首次保存）');
      final savedDraftModel = await contentService.saveDraft(contentSave);

      // 保存成功后，获取新创建的草稿ID和任务信息
      setState(() {
        currentDraftId = savedDraftModel.id;
        // 从第一次保存响应中获取taskRecordId
        if (savedDraftModel.taskRecordId != 0 && actualTaskRecordId == null) {
          actualTaskRecordId = savedDraftModel.taskRecordId;
          taskDetailProv.refreshTaskDetail(
              savedDraftModel.taskRecordId, 'My Tasks');
          taskListProv.refreshTaskList();
          print('从保存草稿响应获取taskRecordId: $actualTaskRecordId');
        }
      });
      print('新草稿创建成功，ID: $currentDraftId');
    }

    apiStopwatch.stop();
    print('草稿API调用完成 (耗时: ${apiStopwatch.elapsedMilliseconds}ms)');

    totalDraftStopwatch.stop();
    print('=== 草稿保存流程完成 ===');
    print(
        '草稿保存总耗时: ${totalDraftStopwatch.elapsedMilliseconds}ms (${(totalDraftStopwatch.elapsedMilliseconds / 1000).toStringAsFixed(2)}秒)');
    print('========================');
  }

  void _saveDraft() async {
    setState(() {
      _isSavingDraft = true;
    });

    try {
      await _performSaveDraft(
          context.read<TaskDetailProv>(), context.read<TaskListProv>());
      _showSaveSuccessToast();
    } catch (e) {
      _showErrorDialog('Draft save failed');
    } finally {
      if (mounted) {
        setState(() {
          _isSavingDraft = false;
        });
      }
    }
  }

  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.grey[900],
        title: Text('Publish failed', style: TextStyle(color: Colors.red)),
        content: Text(message, style: TextStyle(color: Colors.white)),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('Ok', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  // 构建全屏Loading覆盖层
  Widget _buildFullScreenLoading() {
    String loadingText = _isPublishing ? 'Publishing...' : 'Saving Draft...';

    return Positioned.fill(
      child: Material(
        color: Colors.black.withOpacity(0.8), // 半透明黑色背景
        child: Center(
          child: Container(
            padding: EdgeInsets.all(32),
            decoration: BoxDecoration(
              color: Color(0xFF2C2C2C),
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.black26,
                  blurRadius: 10,
                  offset: Offset(0, 4),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: 50,
                  height: 50,
                  child: CircularProgressIndicator(
                    color: Colors.white,
                    strokeWidth: 3,
                  ),
                ),
                SizedBox(height: 20),
                Text(
                  loadingText,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // Add these getter methods:
  List<AssetEntity> get currentPhotos => currentMediaItems
      .where((item) => !item.isNetworkImage && item.type == AssetType.image)
      .map((item) => item.assetEntity!)
      .toList();

  List<AssetEntity> get currentVideos => currentMediaItems
      .where((item) => !item.isNetworkImage && item.type == AssetType.video)
      .map((item) => item.assetEntity!)
      .toList();

  // 添加辅助方法来分离网络图片URL
  List<String> get networkImageUrls => currentMediaItems
      .where((item) => item.isNetworkImage && item.type == AssetType.image)
      .map((item) => item.networkUrl!)
      .toList();

  // 修改标签数据准备逻辑，正确处理任务标签
  List<TaskTagBo> _prepareTaskTagBoList() {
    List<TaskTagBo> taskTagBoList = [];

    // 1. 处理固定标签（从点击按钮添加的）
    final tagProvider = context.read<TagProvider>();
    for (int tagIndex in addedTags) {
      if (tagIndex < tagProvider.tags.length) {
        final tag = tagProvider.tags[tagIndex];
        taskTagBoList.add(TaskTagBo(
          id: tag.id, // 有ID
          name: tag.title, // 标签名称
          type: '1', // 固定标签
        ));
      }
    }

    // 2. 处理自定义标签（从描述文本中提取，包括任务相关标签）
    Set<String> customTags =
        _extractCustomTagsFromText(descriptionController.text);

    // 移除已经在固定标签中的标签名称
    Set<String> fixedTagNames = tagProvider.tags
        .where((tag) => addedTags.contains(tagProvider.tags.indexOf(tag)))
        .map((tag) => tag.displayName.toLowerCase())
        .toSet();

    // 获取任务相关标签的ID（如果存在）
    final taskDetailProv = context.read<TaskDetailProv>();
    Map<String, int?> taskTagIds = {};
    if (taskDetailProv.taskTagsRaw != null) {
      for (var taskTag in taskDetailProv.taskTagsRaw!) {
        String? tagName = taskTag['name'] as String?;
        int? tagId = taskTag['id'] as int?;
        if (tagName != null) {
          taskTagIds[tagName.toLowerCase().replaceAll('#', '')] = tagId;
        }
      }
    }

    for (String customTag in customTags) {
      String normalizedCustomTag = customTag.toLowerCase().replaceAll('#', '');

      if (!fixedTagNames.contains(normalizedCustomTag)) {
        // 检查是否是任务相关标签，如果是则使用其ID
        int? tagId = taskTagIds[normalizedCustomTag];

        taskTagBoList.add(TaskTagBo(
          id: tagId, // 任务标签有ID，自定义标签没有ID
          name: customTag, // 标签名称
          type: tagId != null ? '1' : '2', // 任务标签为固定标签，其他为自定义标签
        ));
      }
    }

    print('=== 标签数据准备完成 ===');
    print('固定标签数量: ${taskTagBoList.where((tag) => tag.type == '1').length}');
    print('自定义标签数量: ${taskTagBoList.where((tag) => tag.type == '2').length}');
    print('任务相关标签ID映射: $taskTagIds');
    print(
        '所有标签: ${taskTagBoList.map((tag) => '${tag.name ?? 'null'}(${tag.type ?? 'null'}, ID:${tag.id ?? 'null'})').join(', ')}');
    print('========================');

    return taskTagBoList;
  }

  // 从文本中提取自定义标签的方法
  Set<String> _extractCustomTagsFromText(String text) {
    Set<String> customTags = {};

    // 使用正则表达式匹配 #标签 格式
    RegExp tagRegex = RegExp(r'#(\w+)', multiLine: true);
    Iterable<RegExpMatch> matches = tagRegex.allMatches(text);

    for (RegExpMatch match in matches) {
      String tagName = match.group(1)!;
      if (tagName.isNotEmpty) {
        customTags.add('#$tagName'); // 保持#前缀
      }
    }

    print('=== 从文本中提取的自定义标签 ===');
    print('原文本: $text');
    print('提取的标签: $customTags');
    print('==============================');

    return customTags;
  }

  // 加载草稿数据
  Future<void> _loadDraftData() async {
    if (widget.taskRecordId == null) return;

    setState(() {
      _isLoadingDraft = true;
    });

    try {
      final contentService = ContentService();
      final draftData =
          await contentService.getDraftByTaskRecordId(widget.taskRecordId!);
      _populateFieldsFromDraft(draftData);
    } catch (e) {
      _showErrorDialog('Failed to load draft \nYou can continue editing.');
      print('Failed to load draft: $e');
    } finally {
      setState(() {
        _isLoadingDraft = false;
      });
    }
  }

  // 构建键盘上方工具栏
  Widget _buildKeyboardToolbar() {
    return Container(
      height: 44,
      decoration: BoxDecoration(
        color: Color(0xFF2C2C2C),
        border: Border(
          top: BorderSide(color: Colors.grey[700]!, width: 0.5),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          TextButton(
            onPressed: () {
              // 关闭键盘
              FocusScope.of(context).unfocus();
            },
            child: Text(
              'done',
              style: TextStyle(
                color: Colors.white, // 修改为白色
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          SizedBox(width: 8),
        ],
      ),
    );
  }

  // 修改发布成功处理
  void _showSubmitSuccessToast() {
    Navigator.of(context).pop();

    // 使用带标题和内容的ToastMenu
    if (mounted) {
      ToastMenu.showToastWithTitle(
        context,
        'Submitted successfully!',
        'We will review your content as soon as possible and notify you.',
      );
    }
  }

  // 修改草稿保存成功处理
  void _showSaveSuccessToast() {
    ToastMenu.showToast(context, 'Saved successfully!');
  }
}
